from server import app
from vim_server import VIM_URl_PREX
import vim_sys
import vim_md
from flask import render_template,request
from pathlib import Path
vim_sys.history_start=50
@app.route(VIM_URl_PREX+'/<path:file_path>',methods=['GET','POST'])
def vim_url(file_path):
    file_path='/'+ file_path
    if file_path == "/log":
        return render_template('log.html',title='log',body=vim_sys.cmd_history)
    elif not Path(file_path).exists():
        pass
    elif file_path.endswith('.dot'):
        cmd_info=vim_sys.execute_os_cmd(f'dot {file_path} -Tsvg')
        print(cmd_info)
        with open(vim_sys.cmd_result_path(cmd_info['std_out'])) as f:
            body= f.read()
            return render_template('markdown.html',title=Path(file_path).name,body=body)
    elif file_path.endswith('.md'):
        body= vim_md.generet(file_path)
        return render_template('markdown_toc.html',title=Path(file_path).name,body=body)
    elif file_path.endswith('.pu') or file_path.endswith('.puml'):
        cmd=request.args.get('cmd')
        svg_dir=vim_sys.temp_dir
        cmd_info=vim_sys.execute_os_cmd(f'{cmd} -o {svg_dir} {file_path}')
        app.logger.info(cmd_info)
        with open(vim_sys.cmd_result_path(Path(file_path).stem,suffix='.svg')) as f:
            body= f.read()
            return render_template('markdown.html',title=Path(file_path).name,body=body)
    else:
        with Path(file_path) as file:
            return file.read_text()

    return file_path

